package com.uhu.code;

import com.uhu.code.help.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 19. 删除链表的倒数第 N 个结点
 * https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked
 */
public class Solution19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode first = head;
        List<ListNode> listNode = new ArrayList<>();
        while (head != null) {
            listNode.add(head);
            head = head.next;
        }
        int size = listNode.size();
        if (size == n) {
            return first.next;
        }
        for (int i = 1; i < size; i++) {
            if (i == size - n) {
                ListNode l = listNode.get(i);
                if (i + 1 < size) {
                    listNode.get(i - 1).next = listNode.get(i + 1);
                } else {
                    listNode.get(i - 1).next = null;
                }
            }
        }
        return first;
    }
}
